package com.market.xg.gateway.filter;

import com.market.xg.common.starter.constant.MDCConstant;
import com.market.xg.common.starter.constant.TraceConstant;
import com.market.xg.common.starter.util.JsonUtils;
import com.market.xg.gateway.utils.GatewayUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class LogFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String traceId = GatewayUtil.getTraceId(exchange.getRequest());
        MDC.put(MDCConstant.TRACE_ID_KEY,traceId);
        log.info("LogFilter filter ");
    return chain.filter(exchange.mutate().request(
            exchange.getRequest().mutate().header(TraceConstant.LOG_TRACE_ID_ON_CDC,traceId).build()).build());
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
